<?php
$APP_CODE = null;
$dir_base = dirname($_SERVER['REQUEST_URI']);
$req_url = $dir_base . "/oAuth_req.php";
$url = "https://oauth.campus.rwth-aachen.de/oauth2waitress/oauth2.svc/code";
$manage_url = "https://oauth.campus.rwth-aachen.de/manage/?q=verify&d=";
$poll_url = $dir_base . "/oAuth_poll.php?device_code=";

if(isset($_GET['delete']) && $_GET['delete'] == 'cookie')
{
	unset($_COOKIE['APP_CODE']);
	setcookie("APP_CODE", null, -1, '/');
}
if(isset($_GET['APP_CODE']))
{
	setcookie("APP_CODE", $_GET['APP_CODE'], time() + (1 * 30 * 24 * 60 * 60)); //remember for 1 month
	$APP_CODE = $_GET['APP_CODE'];
}
else if(!isset($_COOKIE['APP_CODE']))
{
	echo "Type your CLIENT-ID:<BR/>";
	echo "<form action='" . $req_url . "'";
	echo "<input type='text' size=200 name='APP_CODE' value=''/>";
	echo "<br/><small>Caution: this client id contatins both UPPER-CASE and lower-case, so double check it when you copy from your mail.</small>";
	echo "<br/><input type='submit' value='Submit'/>";
	echo "</form>";
	die;
}
else
	$APP_CODE = $_COOKIE['APP_CODE'];//'EdtXGQg4npM5FJtG3eEQd0ofTEOTGdDuN9AehN2LcrUJndiBRRbH7e4JGSFXZXfR.apps.rwth-aachen.de';

$parameter = array(
	'scope' => 'l2p2013.rwth',
	'client_id' => $APP_CODE
);

$opts = array(
	CURLOPT_SSL_VERIFYPEER => FALSE,
	CURLOPT_RETURNTRANSFER => true,
	CURLOPT_USERAGENT => 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)',
	
	CURLOPT_URL => $url,
	CURLOPT_POSTFIELDS => http_build_query( $parameter),
	CURLOPT_POST => TRUE,
	
	CURLOPT_HEADER => FALSE
);

$ch = curl_init();
curl_setopt_array($ch, $opts);
$result = curl_exec($ch);
$info = curl_getinfo($ch);

//{"status":"ok","device_code":"ufojODGUsFxir3uF8lca7GDtpEfeOTki","expires_in":1800,"interval":5,"user_code":"MXLPEWAYNL","verification_url":"https:\/\/service.campus.rwth-aachen.de\/oauth2\/oauth2.svc\/manage"}

echo '<pre>';
	echo "<strong>Response from server:</strong><br/>";
	print_r($result);
echo '</pre>';

curl_close($ch);

$jsonObject = json_decode($result, true);

$manage_url .= $jsonObject['user_code'];
$poll_url .= $jsonObject['device_code'].'&APP_CODE='.$APP_CODE;
?>
<pre>
<a href="<?PHP echo $manage_url ?>" target="_BLANK">Authorize here with the device code</a>
<br/>
<a href="<?PHP echo $poll_url; ?>" target="_BLANK">Poll for OAuth token</a>
</pre>
<BR/>
<BR/>
<?PHP echo "<strong>CLIENT-ID from cookie: </strong>".$APP_CODE.'<br/>';?>
<a href="<?PHP echo $req_url; ?>?delete=cookie" target="_BLANK">Clear CLIENT-ID</a>









